package cn.org.timespace.easyframe.action.permission;

import java.io.PrintWriter;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.org.timespace.easyframe.action.EFBaseAction;
import cn.org.timespace.easyframe.model.permission.EfRole;
import cn.org.timespace.easyframe.service.permission.EfRoleService;

/**
 * 角色管理
 * 
 * @author wubo
 * 
 */
public class EFRoleAction extends EFBaseAction {

	private static final String GIVE_LIMIS = "giveLimits";
	
	EFRoleModel efRoleModel=(EFRoleModel)this.getModel();

	public EFRoleAction() {
		super(new EFRoleModel());
	}

	private EFRoleModel getEfRoleModel() {
		return (EFRoleModel) this.getModel();
	}

	private EfRoleService efRoleService;

	public EfRoleService getEfRoleService() {
		return efRoleService;
	}

	public void setEfRoleService(EfRoleService efRoleService) {
		this.efRoleService = efRoleService;
	}

	// 查询所有角色
	public String doList() throws Exception {
		EFRoleModel eFRoleModel=getEfRoleModel();
		List<EfRole> list = efRoleService.findByCondition(eFRoleModel);
		getRequest().setAttribute(VOLIST, list);
		return this.LIST;
	}

	// 根据id查找一个角色
	public String doFindById() throws Exception {
		String roleId = getEfRoleModel().getRoleId();
		if(!StringUtils.isEmpty(roleId)){
		List<EfRole> resList = efRoleService.findByCondition(getEfRoleModel());
		if(resList != null && resList.size() == 1){
			getEfRoleModel().setEfRole(resList.get(0));
		}
		return this.UPDATE;
		}
		return this.ADD;
	}

	// 添加一个角色
	public String doSave() throws Exception {
		EfRole efRole = getEfRoleModel().getEfRole();
		efRoleService.save(efRole);
		return this.doList();
	}

	// 根据id修改指定
	public String doUpdate() throws Exception {
		EfRole efRole = getEfRoleModel().getEfRole();
		efRoleService.update(efRole);
		return this.doList();
	}

	// 根据id删除角色
	public String doDelete() throws Exception{
		String roleId = getRequest().getParameter("roleId");
		if(roleId != null&& !roleId.equals("")){
			efRoleService.deleteRole(roleId);
		}
		
		getEfRoleModel().setRoleId(null);
		return this.doList();
	}
	
	/**
	 * 给角色授权之前
	 * @return
	 * @throws Exception
	 */
	public String doGiveLimitsBefore() throws Exception {
		return GIVE_LIMIS;
	}
	
	/**
	 * 校验角色名称是否存在
	 * @return 存在返回 true 不存在返回false
	 * @throws Exception
	 */
	public String doCheckRoleNameIsExist() throws Exception{
		String result = "true"; //存在
		
		List efRoleList = efRoleService.findByCondition(efRoleModel);
		if(efRoleList.size() == 0){
			result = "false"; //不存在
		}
		
		getResponse().setCharacterEncoding("UTF-8");
		PrintWriter out = getResponse().getWriter();
		out.write(result);
		
		return null;
	}
}
